﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Extensions;
using Abp.UI;
using Xugege.AbpExtension.Application.Extension.Common.Dto;
using Xugege.AbpExtension.Com.Helper;
using Xugege.AbpExtension.Com.Helper.Image;
using Xugege.AbpExtension.Core.Extension.File;

namespace Xugege.AbpExtension.Application.Extension.Common
{
    public class QrCodeGrenrateService : AbpZeroTemplateAppServiceBase, IQrCodeGrenrateService
    {
        private readonly IAppFolders _appFolders;
        private readonly IAppFolderExtension _appFolderExtension;
        public QrCodeGrenrateService(IAppFolders appFolders, IAppFolderExtension appFolderExtension)
        {
            _appFolders = appFolders;
            _appFolderExtension = appFolderExtension;
        }

        /// <summary>
        /// 生成二维码 返回二维码图片地址
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> GetQRCode(GetQRCodeInputDto input)
        {
            var filePath = QRCode(input);
            return await Task.FromResult(_appFolderExtension.GetRelativePath(filePath));
        }

        private string QRCode(GetQRCodeInputDto input)
        {
            if (input.Text.IsNullOrEmpty()) throw new UserFriendlyException("写入信息不能为空");
            string filePath = Path.Combine(_appFolders.TempFileDownloadFolder, $"{StringHelper.CreateIdByGuidAndTime()}.png");
            QrCodeHelper.GenreateQrCode(input.Text, filePath);
            return filePath;
        }

        /// <summary>
        /// 生成二维码 返回二维码图片base64字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> GetQRCodeBase64(GetQRCodeInputDto input)
        {
            var filePath = QRCode(input);
            var qrBytes = System.IO.File.ReadAllBytes(filePath);
            return await Task.FromResult("data:image/png;base64," + Convert.ToBase64String(qrBytes));
        }
    }
}
